package com.axjy.config.etc;

import com.axjy.service.UserService;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.mgt.SecurityManager;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Resource
    private UserService userService;


    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager());
        bean.setLoginUrl("/login");
        Map<String,String> map=new HashMap<>();
        map.put("/logout"," logout");
        map.put("/login","anon");
        map.put("/webjars/**","anon");
        map.put("/attach/**","anon");
        map.put("/**","authc");
        bean.setFilterChainDefinitionMap(map);
        return bean;
    }


     @Bean
     public SecurityManager securityManager(){
         DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
         securityManager.setRealm(smbmsRealm());
         return securityManager;
     }


     @Bean
     public HashedCredentialsMatcher credentialsMatcher(){
          HashedCredentialsMatcher matcher=new HashedCredentialsMatcher();
          matcher.setHashAlgorithmName("md5");
          matcher.setHashIterations(1);
          return matcher;
     }

     @Bean
     public SmbmsRealm smbmsRealm(){
         SmbmsRealm smbmsRealm=new SmbmsRealm();
         smbmsRealm.setUserService(userService);
         smbmsRealm.setCredentialsMatcher(credentialsMatcher());
         return smbmsRealm;
     }

}
